package cn.zmwh.bbs.modules.ums.service;

import cn.hutool.core.util.StrUtil;
import cn.zmwh.bbs.modules.ums.pojo.entity.User;
import cn.zmwh.bbs.modules.ums.mapper.UserMapper;
import cn.zmwh.bbs.modules.ums.pojo.request.RegisterRequest;
import cn.zmwh.common.core.api.Result;
import cn.zmwh.common.core.exception.RRException;
import cn.zmwh.common.core.utils.I18nUtils;
import cn.zmwh.common.security.base.BaseUserDetails;
import cn.zmwh.common.security.base.UserService;
import cn.zmwh.common.security.pojo.dto.LoginDTO;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashSet;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author dmzmwh
 * @since 2025-07-18
 */
@Service
public class UserInfoService extends ServiceImpl<UserMapper, User> implements UserService, UserDetailsService {

    @Autowired
    PasswordEncoder passwordEncoder;

    private UserDetails userToUserDetails(User tlUser,boolean password) {
        Integer enabled = tlUser.getEnabled() == null ? 1 : tlUser.getEnabled();
        if (enabled == 2) {
            throw new RRException(I18nUtils.getWithDefault("user.forbidden", "账号被禁用！"));
        }
        Long id = tlUser.getId();
        String username = tlUser.getName();
        String nick = tlUser.getNick();
        BaseUserDetails userDetail = new BaseUserDetails(id, id, nick, username, password ? tlUser.getPassword() : "", new HashSet<>());
        return userDetail;
    }

    /**
     * 用户查询信息，内部可做邀请 用户注册等
     *
     * @param request
     * @return
     */
    @Override
    public UserDetails loadUser(LoginDTO request) {
        String mobile = request.getMobile();
        User user = baseMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getName, mobile));
        if (user == null) {
            throw new UsernameNotFoundException(I18nUtils.get("user.username_not"));
        }
        return userToUserDetails(user, true);
    }

    @Override
    public UserDetails loadUserById(Long id1) {
        return null;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = baseMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getName, username));
        if (user == null) {
            throw new UsernameNotFoundException(I18nUtils.get("user.username_not"));
        }
        return userToUserDetails(user, false);
    }

    public Result register(RegisterRequest request) {
        String userName = request.getUserName();
        if (StrUtil.isBlank(userName)) {
            return Result.failed(I18nUtils.getWithDefault("user.username_not_null", "用户名不能为空！"));
        }
        User user = baseMapper.selectOne(Wrappers.<User>lambdaQuery()
                .eq(User::getName, userName));
        if (user != null) {
            return Result.failed(I18nUtils.getWithDefault("user.username_exist","账号已存在！"));
        }
        user = new User();
        user.setName(userName);
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setNick(request.getNickName());
        baseMapper.insert(user);
        return Result.success();
    }
}
